<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="230px" style="height: 100vh; display: flex; flex-direction: column;">
        <div style="display: flex; justify-content: center; padding: 15px; flex-shrink: 0;">
          <el-button type="primary" round @click="createNewConversation" style="width: 200px; height: 50px">
            新建对话
            <el-icon class="plus-icon">
              <Plus/>
            </el-icon>
          </el-button>
        </div>
        <div class="sidebar-container">
          <div class="sidebar-list">
            <div
              v-for="conversation in conversations"
              :key="conversation.sessionId"
              class="sidebar-title"
              :class="{ active: currentConversationId === conversation.sessionId }"
              @click="switchConversation(conversation.sessionId)"
            >
              <span class="title-text">{{ conversation.title }}</span>
              <el-icon class="delete-icon" @click.stop="deleteConversation(conversation.sessionId, $event)">
                <Delete />
              </el-icon>
            </div>
          </div>
        </div>
      </el-aside>
      <el-container style="justify-content: center;">
        <div style="display: flex;flex-direction: column;justify-content: center;justify-items: center">
          <router-view :key="$route.params.sessionId" />
        </div>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { v4 as uuidv4 } from 'uuid';
import axios from "axios";
import { warning, success } from "@/message/messageApi";

interface ChatMessage {
  sessionId: string;
  role: string;
  part: string;
  isThinking?: boolean;
}

interface Conversation {
  sessionId: string;
  title: string;
  messages: ChatMessage[];
  lastActive: number;
}

const route = useRoute();
const router = useRouter();
const inputValue = ref('');
const conversations = ref<Conversation[]>([]);
const currentConversationId = ref<string>('');
const isSending = ref(false);
const currentConversation = ref<Conversation | null>(null);

function generateConversationId() {
  return uuidv4();
}

function createNewConversation() {
  const newSessionId = generateConversationId();
  const newConversation: Conversation = {
    sessionId: newSessionId,
    title: '新对话',
    messages: [],
    lastActive: Date.now()
  };

  conversations.value.unshift(newConversation);
  switchConversation(newSessionId);
  router.push({ name: 'chat-session', params: { sessionId: newSessionId } });
}

function switchConversation(sessionId: string) {
  const conversation = conversations.value.find(c => c.sessionId === sessionId);
  if (conversation) {
    currentConversationId.value = sessionId;
    currentConversation.value = conversation;

    if (route.params.sessionId !== sessionId) {
      router.push({ name: 'chat-session', params: { sessionId } });
    }
  }
}

async function deleteConversation(sessionId: string, event: Event) {
  event.stopPropagation();
  try {
    await axios.delete(
      `http://127.0.0.1:8888/ai/deleteConversation?sessionId=${sessionId}&username=${localStorage.getItem("uid")}`
    );

    conversations.value = conversations.value.filter(c => c.sessionId !== sessionId);

    if (currentConversationId.value === sessionId) {
      if (conversations.value.length > 0) {
        switchConversation(conversations.value[0].sessionId);
      } else {
        createNewConversation();
      }
    }

    success("对话已删除");
  } catch (error) {
    console.error("删除对话失败:", error);
    warning("删除对话失败，请重试");
  }
}

async function getUserChatHistoryMessage() {
  try {
    const response = await axios.get(
      `http://localhost:8888/ai/getChatHistoryMessage?username=${localStorage.getItem("uid")}`
    );

    const resData = response.data.data;
    if (resData.length > 0) {
      resData.forEach(session => {
        const messages: ChatMessage[] = [];

        session.msg.forEach(msgItem => {
          if (msgItem.type === "USER") {
            messages.push({
              sessionId: session.sessionId,
              role: "user",
              part: msgItem.contents[0].text
            });
          } else if (msgItem.type === "AI") {
            messages.push({
              sessionId: session.sessionId,
              role: "assistant",
              part: msgItem.text
            });
          }
        });

        const conversation: Conversation = {
          sessionId: session.sessionId,
          title: messages[0]?.part ?
            (messages[0].part.length > 20
              ? messages[0].part.substring(0, 20) + '...'
              : messages[0].part)
            : '无标题对话',
          messages: messages,
          lastActive: session.lastActive || Date.now()
        };

        conversations.value.push(conversation);
      });

      conversations.value.sort((a, b) => b.lastActive - a.lastActive);

      if (conversations.value.length > 0 && !route.params.sessionId) {
        switchConversation(conversations.value[0].sessionId);
      }
    }
  } catch (error) {
    console.error("获取聊天记录失败:", error);
  }
}

// 监听路由变化
watch(() => route.params.sessionId, (newSessionId) => {
  if (newSessionId && currentConversationId.value !== newSessionId) {
    const conversation = conversations.value.find(c => c.sessionId === newSessionId);
    if (conversation) {
      currentConversationId.value = newSessionId;
      currentConversation.value = conversation;
    } else if (conversations.value.length > 0) {
      router.push({ name: 'chat-session', params: { sessionId: conversations.value[0].sessionId } });
    } else {
      createNewConversation();
    }
  }
});

onMounted(() => {
  getUserChatHistoryMessage();

  setTimeout(() => {
    if (conversations.value.length === 0 && !route.params.sessionId) {
      createNewConversation();
    }
  }, 500);
});
</script>

<style >
.common-layout{
  display: flex;
  height: calc(100vh - 10% - 50px);
}

.sidebar-container {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;

}

.sidebar-list {
  display: flex;
  flex-direction: column;
  padding: 0 15px 15px;
  width: 200px;
  overflow-y: auto;
  flex: 1;
  gap: 10px;
  transition: 1.5s;
}

.sidebar-title {
  height: 38px;
  min-width: 200px;
  max-width: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
  border-radius: 10px;
  padding: 0 10px;
  flex-shrink: 0;
  cursor: pointer;
  box-sizing: border-box;
  transition: 1.5s;
}

.title-text {
  display: inline-block;
  width: 180px; /* 固定文本宽度 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 15px;
  text-align: left;
}

.sidebar-title:hover {
  background-color: #deeaf8;
  border-radius: 10px;
  color: #ffffff;
  transition: all 0.3s ease;
}

/* 当前选中对话的样式 */
.sidebar-title.active {
  background-color: #deeaf8;
  color: #ffffff;
}



textarea {
  flex: 1;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 10px;
  resize: none;
  font-size: 20px;
}
textarea::placeholder {
  font-size: 20px;
  align-items: center;
}
textarea:focus {
  border-color: #409eff;
  outline: none;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
}

button {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  width: 90px;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}



.footer text {
  font-size: 9px;
  color: #bdbec1;
}



.markdown-content h1, .markdown-content h2, .markdown-content h3 {
  color: #333;
}

.content .markdown-content think pre code {
  background: #f4f4f4;
  padding: 2px 4px;
  border-radius: 4px;
}

.delete-icon {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.delete-icon:hover {
  opacity: 1;
}

.markdown-content {
  font-size: 16px;
  border-radius: 15px;
  padding: 15px;
}

/* 代码块样式 */
.markdown-content pre {
  background-color: #eae9e9 !important;
  border-radius: 6px !important;
  padding: 16px !important;
  margin: 12px 0 !important;
  overflow-x: auto;
}

.markdown-content code:not(pre code) {
  background-color: transparent !important;
  padding: 2px 4px;
  border-radius: 4px;
}

.markdown-content pre code {
  background-color: transparent !important;
  color: inherit !important;
  padding: 0 !important;
}

/* 确保行号和代码对齐 */
.markdown-content .hljs {
  display: block;
  overflow-x: auto;
  padding: 1em;
}
</style>
